package com.thinklib.controller;

import com.thinklib.bean.User;
import com.thinklib.service.AuthService;
import com.thinklib.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/api/v1/user/")
public class AuthController {

	@Resource
	private AuthService authService;
	
	// 登录并校验
	@PostMapping("login")
	@ResponseBody
	public JsonData loginAction(@RequestParam("email") String email, @RequestParam("password") String password, HttpServletResponse response) {
		String token = authService.findUserByUsername(email, password);
		return token == null ? JsonData.buildError("账号或密码不正确") : JsonData.buildSuccess(token);
	}

	// 注册账号
	@RequestMapping("register")
	@ResponseBody
	public JsonData register(HttpServletRequest request,
							 @RequestParam("email") String email,
							 @RequestParam("phone") String phone,
							 @RequestParam("nickname") String nickname,
							 @RequestParam("password") String password,
							 @RequestParam("sex") int sex) {

		// 防止重复注册
		User user = authService.findUserByEmail(email);
		if (user != null) {
			return JsonData.buildError("该邮箱已经注册");
		}
		JsonData jsonData = authService.register(request,email,phone,nickname,password,sex);
		return jsonData;
	}
	
	// 激活账号服务
	@RequestMapping("/activation")
	public String activationEmail(@RequestParam("code") String code) {
		User user = authService.findUserByCode(code);
		if (!StringUtils.isEmpty(user)) {
			int affectLine = authService.activationEmail(code);
			if (affectLine == 1) {
				return "index";
			}
		}
		return "error";
	}
	
}
